package com.mgface.zookeeper.premitive;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class Base {
	private static Logger log = Logger.getLogger(Base.class);
	private static ZooKeeper client;
	private static final String path = "/pub-sub-a";
	private static final String v_path = path + "/v1";

	public static void main(String[] args) throws Exception {
		CountDownLatch on = new CountDownLatch(1);
		client = new ZooKeeper("localhost:2181,localhost:2182,localhost:2183", 10_000, e -> {
			try {
				if (e.getState() == KeeperState.SyncConnected) {
					switch (e.getType()) {
					case None:
						if (e.getPath() == null) {
							on.countDown();
						}
						break;
					case NodeCreated:
						Stat stat = new Stat();
						byte[] v = client.getData(path, true, stat);// 获取数据，并且监听path节点的变动
						log.info("节点创建成功:" + new String(v));
						break;
					case NodeDeleted:
						log.info("节点:" + path + "被删除");
						break;
					case NodeDataChanged:
						Stat stat2 = new Stat();
						byte[] v2 = client.getData(path, true, stat2);
						log.info("新值:" + new String(v2));
						break;
					case NodeChildrenChanged:
						List<String> list = client.getChildren(path, true);// 获取子节点的相对路径，并且监听子节点的列表变化
						log.info("节点变化:" + list);
						break;
					default:
						break;
					}
				}
			} catch (Exception error) {
				error.getMessage();
			}

		});
		log.info("ZK状态:" + client.getState().toString());
		on.await();
		log.info("zookeeper session 建立完成");
		Stat stat = client.exists(path, true);// 给当前节点设置监控
		log.info("节点:" + (stat == null ? "不存在" : "存在"));
		client.create(path, "init".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
		log.info("success create znode:" + path);
		// client.setData(path, "init2".getBytes(), stat.getVersion());
		client.setData(path, "init2".getBytes(), -1);
		client.setData(path, "init3".getBytes(), -1);
		client.getChildren(path, true);//给子节点列表添加监控
		client.create(v_path, "{connection:mysql,password:123456}".getBytes(), Ids.OPEN_ACL_UNSAFE,CreateMode.EPHEMERAL);
		client.getData(v_path, e->{
			try {
				System.out.println(e.getType()+"|"+new String(client.getData(v_path, false, null)));
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}, stat);//对子节点变化添加监控
		client.setData(v_path, "{connection:oracle,password:123456789}".getBytes(), -1);
		client.delete(v_path, -1);
		client.delete(path, -1);
		TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
	}

}
